<?php

namespace app\index\controller;
use GatewayClient\Gateway;  //引入composer
//use think\gateway\Gateway;
use think\Controller;
use think\Request;
use app\index\controller\Wx;
use app\index\controller\Location;
class Index extends Controller
{
    /**
     * 发送方法
     * @param Request $request
     * @param $sex
     * @param $client_id
     * @param $message
     * @param $room_id
     * @param string $img
     * @param string $front
     * @param string $audio
     * @param string $localId
     */
    public function send(Request $request,$sex,$client_id,$message="",$room_id,$img="",$front="",$audio="",$localId="")
    {
        $user_name=$request->has('user_name','post') ? $request->param('user_name') : "";

        $date=date("Y-m-d H:i");
        if ($img=="img"){
            $send=[
                "sex"=>$sex,
                "client_id"=>$client_id,
                "message"=>$message,
                "room_id"=>$room_id,
                "date"=>$date,
                "type"=>"img",
                "user_name"=>$user_name
            ];

        }elseif ($audio=="audio"){  //语音发送
            $send=[
                "sex"=>$sex,
                "client_id"=>$client_id,

                "room_id"=>$room_id,
                "date"=>$date,
                "type"=>"audio",
                "localId"=>$localId,
                "user_name"=>$user_name
            ];

        }else{      //文字发送
            $message=htmlspecialchars($message);
            $send=[
                "sex"=>$sex,
                "client_id"=>$client_id,
                "message"=>$message,
                "room_id"=>$room_id,
                "date"=>$date,
                "type"=>"build",
                "user_name"=>$user_name
            ];
        }

        $address=$request->param("address");

        $address!="0" && $send['address']=$address;

        $send=json_encode($send);

        Gateway::sendToGroup($room_id,$send);
    }

    public function index(Request $request)
    {

        
        $param=$request->url();
        $wxConfig=$this->say($param);
     
        $this->assign("wxConfig",$wxConfig);
        return view();
    }

    /**
     * 进入聊天室方法(绑定)
     * @param Request $request
     * @param $client_id
     * @param $username
     * @param $sex
     * @return string
     */
    public function bind(Request $request, $client_id, $username, $sex)
    {
        $userMessage = [
            "user_name" => $username,
            "sex" => $sex,
            "client_id" => $client_id,
            "status" => 1 //是否正在匹配对象? 1代表正在匹配
        ];
        $haveWxAddress=$request->has('wxAddress','post');

        if ($haveWxAddress){
            $userMessage['longitude']=$request->param('longitude');
            $userMessage['latitude']=$request->param('latitude');
            $userMessage['address']=$request->param('address');
            $userMessage['wxAddress']=$request->param("wxAddress");
            $userMessage['chatAddress']=$request->param("chatAddress");
        }

        Gateway::setSession($client_id, $userMessage);   //写入缓存

        $code=$this->find($userMessage);

        return $code;
    }

    /**
     * 匹配对象方法
     * @param $userMessage [当前用户的信息]
     */
    public function find($userMessage)  //寻找对象
    {

        $room_id = rand(2, 100) + time();

        $i = 0;   //匹配时间为30秒

            while (1) {   //进入匹配

                $allClient = Gateway::getAllClientSessions(); //获取全体用户状态信息
                $mySession = Gateway::getSession($userMessage['client_id']); //获取我的信息
		if(!Gateway::isOnline($userMessage['client_id'])){
                    break;
                }
                if (!empty($mySession['room_id'])) { //我若已经被别人分组,则直接弹出

                    $code = [
                        "code" => 200,
                        "room_id" => $mySession['room_id'],
                        "client_id" => $mySession['client_id'],
                        "user_name" => $mySession['user_name'],
                        "sex" => $mySession['sex'],
                        "message" => "匹配成功"
                    ];


                    return json_encode($code);

                }

                foreach ($allClient as $key=>$client) {

                    if (empty($client['status'])){      //抛除在大厅的用户
                        continue;
                    }

                    if ($client['client_id'] != $userMessage['client_id'] && $client['sex'] != $userMessage['sex'] && empty($client['room_id'])) {

                        Gateway::joinGroup($client['client_id'], $room_id);

                        Gateway::joinGroup($userMessage['client_id'], $room_id);

                        $add_room_id = ["room_id" => $room_id];

                        Gateway::updateSession($client['client_id'], $add_room_id);

                        Gateway::updateSession($userMessage['client_id'], $add_room_id);

                        $he_message=[
                            "he_or_she_id"=>$userMessage['client_id'],
                            "he_or_she_name"=>$userMessage['user_name']
                        ];

                        Gateway::updateSession($client['client_id'],$he_message);

                            $he_message=[
                                "he_or_she_id"=>$client['client_id'],
                                "he_or_she_name"=>$client['user_name']
                            ];

                            Gateway::updateSession($userMessage['client_id'],$he_message);

                        $code = [
                            "code" => 200,
                            "room_id" => $room_id,
                            "client_id" => $mySession['client_id'],
                            "user_name" => $mySession['user_name'],
                            "sex" => $mySession['sex'],
                            "message" => "匹配成功"
                        ];
                        return json_encode($code);
                    }
                }
                sleep(1);
                $i++;

                if ($i == 30) {
                    Gateway::setSession($userMessage['client_id'],[]);  //重置用户缓存,用于解决在大厅中还能被匹配的BUG
                    $code = [
                        "code" => 404,
                        "message" => "抱歉~貌似这个点没有能和你匹配的异性呢~~"
                    ];


                    return json_encode($code);
                }

            }


    }


    /**
     * 进入房间
     * @param string $room_id
     * @param string $client_id
     * @param string $sex
     * @param string $user_name
     * @return mixed
     */
    public function room($room_id="",$client_id="",$sex="",$user_name="")
    {
        $seesion_group=Gateway::getClientSessionsByGroup($room_id);

        $title=array();

        $haveWxAddressCount=0;  //判断房间中两个人,是否都开启了微信定位,初始值为0
        $haveWxAddressUser=array();
        foreach ($seesion_group as $key=>$value){

            $title[]=$value['user_name'];

            if(isset($value['wxAddress'])){
                //并且记录该用户的client_id
                $haveWxAddressUser[]=$key;
                $haveWxAddressCount++;
            }

        }

        $count=Gateway::getClientIdCountByGroup($room_id);  //获取当前房间内的人数
        $mySession=Gateway::getSession($client_id);    //获取当前用户的缓存
        $title=implode("与",$title);
        $title="欢迎".$title."进入房间";
        $room_Message=[
            "room_id"=>$room_id,
            "client_id"=>$client_id,
            "sex"=>$sex,
            "user_name"=>$user_name,
            "room_titile"=>$title,
            "room_count"=>$count
        ];

        if (!$haveWxAddressCount){

            //都没有开启微信的情况下

        }else{

            if($haveWxAddressCount==1){
                //只有一个用户开启了定位,判断这个用户是不是我自己

                if(isset($mySession['wxAddress'])){
                    $room_Message['wxAddress']=true;
                    $room_Message['longitude']=$mySession['longitude']; //经度
                    $room_Message['latitude']=$mySession['latitude'];   //纬度
                    $room_Message['address']=$mySession['chatAddress'];
                }
            }elseif ($haveWxAddressCount==2){
                for ($i=0;$i<2;$i++){
                     if($i==0){
                         $originLng=$seesion_group[$haveWxAddressUser[$i]]['longitude'];
                         $originLat=$seesion_group[$haveWxAddressUser[$i]]['latitude'];
                     }else{
                         $destinationsLat=$seesion_group[$haveWxAddressUser[$i]]['latitude'];
                         $destinationsLng=$seesion_group[$haveWxAddressUser[$i]]['longitude'];
                     }
                }
                $location=new Location();
                $data=$location->computeDistance($originLat,$originLng,$destinationsLat,$destinationsLng);
                $room_Message['distance']=$data['text'];    //双方公里数
                $room_Message['address']=$mySession['chatAddress'];
            }

        }


        $this->assign("data",$room_Message);

        return view();
    }


    /**
     * 上传图片
     * @return string
     */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        $info = $file->validate(['size' => 3048576, 'ext' => 'jpg,png,gif,jpeg'])->move('./uploads');
        // 移动到框架应用根目录/uploads/ 目录下
        if ($info) {

            $saveName=$info->getSaveName();

            $replace=str_replace("\\","/",$saveName);

            $path="../uploads/".$replace;

            return json_encode(["code"=>"200","message"=>"发送成功","path"=>$path]);
        } else {
            return json_encode(["code"=>"400","message"=>$file->getError()]);

        }

    }

    /**
     * @return array    调用微信js-sdk
     */
    public function say($param)
    {
        $wx = new Wx();

        $ticket= $wx->getAccessToken()->getJsapiTicket()->jsapi_ticket;

        $timestamp=time();

        $nonceStr="xhy";
        

        if (empty($param)) {
            $join="jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url=http://gzh.xhyonline.com/";    
        }else{
          $join="jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url=http://gzh.xhyonline.com{$param}";  
         
        }

        
          
        $signature=sha1($join);

        return [
           "timestamp"=>$timestamp,
            "nonceStr"=>$nonceStr,
            "signature"=>$signature,
            "appId"=>$wx->appId
        ];
    }
}
